package top.eggcode.plugins.query.clause;

import lombok.Data;
import top.eggcode.plugins.query.canst.JoinType;
import top.eggcode.plugins.query.def.LiteralSentence;

/**
 * Title:
 * Description: TODO
 * Date: 2021/8/24 12:09
 *
 * @author JiaQi Ding
 * @version 1.0
 */
@Data
public class JoinClause implements LiteralSentence {

    private String tableName;

    private String alias;

    private String onObject;

    private JoinType type;

    public JoinClause(String tableName, JoinType type) {
        this.tableName = tableName;
        this.type = type;
    }

    public JoinClause as(String name) {
        this.alias = name;
        return this;
    }

    public JoinClause on(String condition) {
        this.onObject = "on " + condition;
        return this;
    }

    public String getReferenceName() {
        if (this.alias != null) {
            return this.alias;
        }
        return this.tableName;
    }

    @Override
    public String render() {
        StringBuilder joinClause = new StringBuilder();
        String joinType;
        switch (this.type) {
            case INNER:
                joinType = "INNER";
                break;
            case LEFT:
                joinType = "LEFT";
                break;
            case RIGHT:
                joinType = "RIGHT";
                break;
            default:
                joinType = "";
        }
        joinClause.append(joinType).append(" JOIN").append(" ").append(tableName);
        // 处理别名
        if (this.alias != null) {
            joinClause.append(" as ").append(this.alias);
        }
        //关联条件
        joinClause.append(" ").append(this.onObject);

        return joinClause.toString();
    }
}
